#include "web-socket.h"

#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <unistd.h>

int main(int argc, char **argv) {
    int listenfd, connfd, port;
    struct sockaddr_in clientaddr;
	socklen_t clientlen;
	fd_set readfds, testfds;

    if (argc != 2) {
		fprintf(stderr, "usage: %s <port>\n", argv[0]);
		exit(1);
	}
	port = atoi(argv[1]);
	listenfd = openListenfd(port);

	FD_ZERO(&readfds);
	// 将服务器端socket加入到集合中
	FD_SET(listenfd, &readfds);

	while(1) {
		int fd;
		int nread;
		testfds = readfds;
		printf("server waiting\n");

		select(FD_SETSIZE, &testfds, (fd_set *)0,(fd_set *)0, (struct timeval *) 0);
		for(fd = 0; fd < FD_SETSIZE; fd++) {
			/* 找到相关文件描述符*/
			if(FD_ISSET(fd,&testfds)) {
				if(fd == listenfd) {
					clientlen = sizeof(clientaddr);
					connfd = accept(listenfd, (struct sockaddr *)&clientaddr, &clientlen);
					FD_SET(connfd, &readfds);
					printf("adding client on fd %d\n", connfd);
				} else {
					ioctl(fd, FIONREAD, &nread);

					if(nread == 0) {
						close(fd);
						FD_CLR(fd, &readfds);
						printf("removing client on fd %d\n", fd);
					} else {
						processRequest(fd);
					}
				}
			}
		}
	}
}
